package com.zhfi.dataapply.service.impl;

import com.zhfi.dataapply.service.BatchService;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.support.SimpleJobLauncher;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class BatchServiceImpl implements BatchService, ApplicationContextAware {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private SimpleJobLauncher jobLauncher;

    @Override
    public void createBatchJob(String jobName) throws Exception {
        JobParameters jobParameters = new JobParametersBuilder()
                .addString("jobClassName", jobName)
                .addString("uuid", UUID.randomUUID().toString().replace("-",""))
                .toJobParameters();
        Job job = applicationContext.getBean(jobName, Job.class);
        // 传入一个Job任务和任务需要的参数
        jobLauncher.run(job, jobParameters);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
